package com.flycms.web.front.rest;

import com.flycms.config.DruidDataSourceConfigurer;
import com.flycms.constant.Const;
import com.flycms.core.base.BaseController;
import com.flycms.core.entity.PageVo;
import com.flycms.core.entity.RestDataVo;
import com.flycms.core.entity.RestStatusCode;
import com.flycms.core.utils.StringHelperUtils;
import com.flycms.module.question.service.ImagesRestService;
import com.flycms.module.user.model.User;
import com.flycms.module.user.model.UserFans;
import com.flycms.module.user.model.UserInfo;
import com.flycms.module.user.service.UserRestService;
import com.flycms.utils.ConvertUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/rest/user")
public class UserRestController extends BaseController {
    @Autowired
    protected UserRestService userService;
    @Autowired
    DruidDataSourceConfigurer dataSourceConfigurer;
    @Autowired
    private ImagesRestService imagesService;

    //没有权限的跳转
    @GetMapping("/nullPermission")
    @ResponseBody
    public RestDataVo nullPermission() {
        RestDataVo dataVo = new RestDataVo();
        dataVo.setMsg("此用户没有访问权限");
        dataVo.setCode(403);
        return dataVo;
    }

    //没有权限的跳转
    @GetMapping("/noLogin")
    @ResponseBody
    public RestDataVo noLogin() {
        RestDataVo dataVo = new RestDataVo();
        dataVo.setMsg("当前没有登陆或登陆失效");
        dataVo.setCode(403);
        return dataVo;
    }

    @GetMapping(value = "/rank")
    @ResponseBody
    public RestDataVo getUserRank(){
        return RestDataVo.OK("查询成功",userService.getUserRank());
    }

    /**
     * 用户提交手机号码申请获取验证码
     *
     * @param username 提交的手机号码
     * @param captcha  验证码
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/u/mobilecode")
    public RestDataVo getAddUserMobileCode(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "captcha", required = false) String captcha) throws Exception {
        RestDataVo data;
        data = checkCode(captcha);
        if (data.getCode() == RestStatusCode.SUCCESS.getStatusCode()) {
            return data;
        }
        if (!StringHelperUtils.checkPhoneNumber(username)) {
            return RestDataVo.ERROR("手机号码错误！");
        }
        data = userService.regMobileCode(username);
        return data;
    }

    /**
     * 添加新用户
     *
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/u/reg_user")
    public RestDataVo addUser(@RequestBody Map<String, Object> params) {
        String username = String.valueOf(params.get("username"));
        String password = String.valueOf(params.get("password"));
        String password2 = String.valueOf(params.get("password2"));
        String captcha = String.valueOf(params.get("captcha"));
        try {
            username = username.trim();
            password = password.trim();
            password2 = password2.trim();
            captcha = captcha.trim();
            RestDataVo data = checkCode(captcha);
            if (data.getCode() != RestStatusCode.SUCCESS.getStatusCode()) {
                return data;
            }

            if (StringUtils.isBlank(username)) {
                return RestDataVo.ERROR("用户名不能为空");
            }
            if (StringUtils.isBlank(password)) {
                return RestDataVo.ERROR("密码不能为空");
            }
            if (password.length() < 6) {
                return RestDataVo.ERROR("密码不能小于6位");
            }
            if (password.length() > 16) {
                return RestDataVo.ERROR("密码不能大于16位");
            }
            if (!password.equals(password2)) {
                return RestDataVo.ERROR("密码两次输入不一致");
            }
            Integer userType = 3;
            if (StringHelperUtils.checkPhoneNumber(username)) {
                userType = 1;
            } else if (StringHelperUtils.emailFormat(username)) {
                userType = 2;
            }
            return userService.addUserReg(userType, username, password, null, null, request, response);
        } catch (Exception e) {
            return RestDataVo.ERROR(e.getMessage());
        }
    }

    @ResponseBody
    @PostMapping(value = "/u/addMobileUser")
    public RestDataVo addMobileUser(@RequestBody Map<String, Object> params) throws Exception {
        String phoneNumber = String.valueOf(params.get("phoneNumber"));
        String password = String.valueOf(params.get("password"));
        String password2 = String.valueOf(params.get("password2"));
        //邀请人id（暂时不用）
        //String invite=String.valueOf(params.get("invite"));
        String invite = null;
        String mobilecode = String.valueOf(params.get("mobilecode"));
        if (mobilecode == null) {
            return RestDataVo.ERROR("验证码不能为空");
        }
        if (password == null) {
            return RestDataVo.ERROR("密码不能为空");
        }
        if (!password.equals(password2)) {
            return RestDataVo.ERROR("两次密码输入不一样");
        }
        return userService.addUserReg(1, phoneNumber, password, mobilecode, invite, request, response);
    }


    /**
     * 登录处理
     *
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/u/login_act")
    public RestDataVo userLogin(@RequestBody Map<String, Object> params) {
        String username = String.valueOf(params.get("username"));
        String password = String.valueOf(params.get("password"));
        String rememberMe = String.valueOf(params.get("rememberMe"));
        String captcha = String.valueOf(params.get("captcha"));
        try {
            if (StringUtils.isBlank(username)) {
                return RestDataVo.ERROR("用户名不能为空");
            }
            if (StringUtils.isBlank(password)) {
                return RestDataVo.ERROR("密码不能为空");
            } else if (password.length() < 6 && password.length() > 30) {
                return RestDataVo.ERROR("密码最少6个字符，最多30个字符");
            }
            RestDataVo data = checkCode(captcha);
            if (data.getCode() != RestStatusCode.SUCCESS.getStatusCode()) {
                return data;
            }
            boolean keepLogin = "1".equals(rememberMe) ? true : false;
            //登陆校验
            User entity = userService.userLogin(username, password, keepLogin, request, response);
            if (entity == null) {
                return RestDataVo.ERROR("帐号或密码错误。");
            } else {
                session.removeAttribute(Const.KAPTCHA_SESSION_KEY);
                return RestDataVo.OK("登陆成功", entity);
            }
        } catch (Exception e) {
            return RestDataVo.ERROR("服务器错误，异常：" + e.getMessage());
        }
    }

    /**
     * 更新用户基本信息
     *
     * @param user
     * @param result
     * @return
     */
    @PostMapping("/u/account_update")
    @ResponseBody
    public RestDataVo updateUserAccount(@RequestBody @Valid User user, BindingResult result) {
        RestDataVo data = RestDataVo.ERROR("操作失败");
        try {
            if (result.hasErrors()) {
                List<ObjectError> list = result.getAllErrors();
                for (ObjectError error : list) {
                    return RestDataVo.ERROR(error.getDefaultMessage());
                }
                return null;
            }
            if (!StringUtils.isNumeric(user.getUserId().toString())) {
                return RestDataVo.ERROR("请勿非法传递数据！");
            }
            if (!user.getUserId().equals(getUser().getUserId())) {
                return RestDataVo.ERROR("请勿非法传递数据！");
            }
            if (!getUser().getUserId().equals(user.getUserId())) {
                return RestDataVo.ERROR("只能修改属于自己的基本信息！");
            }
//            if (StringUtils.isBlank(user.getNickName())) {
////                return RestDataVo.ERROR("昵称不能为空！");
////            }
            if (StringUtils.isBlank(user.getUserName())) {
                return RestDataVo.ERROR("用户名不能为空！");
            }
//            if (user.getBirthday() == null || "".equals(user.getBirthday())) {
//                return RestDataVo.ERROR("请选择您的生日日期！");
//            }
//            if (DateUtils.isValidDate(user.getBirthday().toString())) {
//                return RestDataVo.ERROR("生日日期格式错误！");
//            }
//            if (user.getProvince() == 0) {
//                return RestDataVo.ERROR("省份未选择！");
//            }
//            if (user.getCity() == 0) {
//                return RestDataVo.ERROR("地区为选择！");
//            }
            data = userService.updateUserAccount(user);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 用户提交手机号码申请获取验证码
     *
     * @param params 提交的手机号码
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/u/safemobilecode")
    public RestDataVo safeMobileCode(@RequestBody Map<String, Object> params) throws Exception {
        String mobile = String.valueOf(params.get("mobile"));
        String captcha = String.valueOf(params.get("captcha"));
        RestDataVo data = checkCode(captcha);
        if (data.getCode() == RestStatusCode.SUCCESS.getStatusCode()) {
            return data;
        }
        if (!StringHelperUtils.checkPhoneNumber(mobile)) {
            return RestDataVo.ERROR("手机号码错误！");
        }
        return userService.safeMobileCode(getUser().getUserId(), mobile);
    }

    /**
     * 安全手机更改绑定
     *
     * @param password
     * @param mobile
     * @param code
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/u/safe_mobile_update")
    public RestDataVo safeMobile(
            @RequestParam(value = "password", required = false) String password,
            @RequestParam(value = "mobile", required = false) String mobile,
            @RequestParam(value = "code", required = false) String code) {
        RestDataVo data;
        try {
            if (StringUtils.isBlank(password)) {
                return RestDataVo.ERROR("密码不能为空");
            } else if (password.length() < 6 && password.length() >= 32) {
                return RestDataVo.ERROR("密码最少6个字符，最多32个字符");
            }
            if (!StringHelperUtils.checkPhoneNumber(mobile)) {
                return RestDataVo.ERROR("手机号码错误！");
            }
            if (code == null && "".equals(code)) {
                return RestDataVo.ERROR("验证码不能为空");
            }
            data = userService.updateSafeMobile(getUser().getUserId(), password, mobile, code);
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 设置安全邮箱
     *
     * @param userEmail
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/u/safe_email_code")
    public RestDataVo userAjaxMailCaptcha(@RequestParam(value = "userEmail", required = false) String userEmail) {
        RestDataVo data;
        try {
            if (!StringHelperUtils.emailFormat(userEmail)) {
                return RestDataVo.ERROR("邮箱格式错误！");
            }
            return userService.safeEmailVerify(userEmail, getUser().getUserId());
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    /**
     * 安全邮箱修改绑定
     *
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/u/safe_email_update")
    public RestDataVo safeEmail(@RequestBody Map<String, Object> params) {
        String password = String.valueOf(params.get("password"));
        String userEmail = String.valueOf(params.get("userEmail"));
        String code = String.valueOf(params.get("code"));
        try {
            // 校验验证码
            if (code == null && "".equals(code)) {
                return RestDataVo.ERROR("验证码不能为空");
            }
            if (StringUtils.isBlank(password)) {
                return RestDataVo.ERROR("新密码不能为空");
            } else if (password.length() < 6 && password.length() >= 32) {
                return RestDataVo.ERROR("密码最少6个字符，最多32个字符");
            }
            if (!StringHelperUtils.emailFormat(userEmail)) {
                return RestDataVo.ERROR("邮箱地址错误！");
            }
            return userService.updateSafeEmail(getUser().getUserId(), password, userEmail, code);
        } catch (Exception e) {
            return RestDataVo.ERROR(e.getMessage());
        }
    }


    /**
     * 个人信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = {"/u/info/{id}", "/u/info"})
    public RestDataVo userInfo(@PathVariable(value = "id", required = false) String id) {
        if (id != null) {
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("参数错误");
            }
            User user = userService.findUserById(Long.parseLong(id), 1);
            UserInfo userInfo = ConvertUtils.sourceToTarget(user, UserInfo.class);
            return RestDataVo.OK(userInfo);
        } else {
            UserInfo userInfo = ConvertUtils.sourceToTarget(getUser(), UserInfo.class);
            return RestDataVo.OK(userInfo);
        }
    }


    /**
     * 密码修改
     *
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/u/password_update")
    public RestDataVo updatePassword(@RequestBody Map<String, Object> params) {
        String old_password = String.valueOf(params.get("old_password"));
        String password = String.valueOf(params.get("password"));
        String password_confirmation = String.valueOf(params.get("password_confirmation"));
        String captcha = String.valueOf(params.get("captcha"));
        RestDataVo data = checkCode(captcha);
        if (data.getCode() == RestStatusCode.SUCCESS.getStatusCode()) {
            return data;
        }
        try {
            if (StringUtils.isBlank(old_password)) {
                return RestDataVo.ERROR("原来密码不能为空");
            } else if (old_password.length() < 6 && old_password.length() >= 32) {
                return RestDataVo.ERROR("密码最少6个字符，最多32个字符");
            }
            if (StringUtils.isBlank(password)) {
                return RestDataVo.ERROR("新密码不能为空");
            } else if (password.length() < 6 && password.length() >= 32) {
                return RestDataVo.ERROR("密码最少6个字符，最多32个字符");
            }
            if (!password.equals(password_confirmation)) {
                return RestDataVo.ERROR("两次密码必须一样");
            }
            session.removeAttribute(Const.KAPTCHA_SESSION_KEY);
            return userService.updatePassword(getUser().getUserId(), old_password, password);
        } catch (Exception e) {
            return RestDataVo.ERROR(e.getMessage());
        }
    }

    /**
     * 保存头像
     *
     * @param params
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @ResponseBody
    @PostMapping("/u/avatar/upload")
    public RestDataVo changeAvatar(@RequestBody Map<String,String> params) throws Exception {
        String avatar = params.get("avatar");
        if (avatar == null || StringUtils.isEmpty(avatar)) {
            return RestDataVo.ERROR("头像不能为空");
        }
        userService.updateAvatar(getUser().getUserId(), avatar);
        return RestDataVo.OK("修改成功");
    }

    //关注用户处理
    @ResponseBody
    @PostMapping(value = "/u/follow/{id}")
    public RestDataVo userFollow(@PathVariable(value = "id", required = false) String id) {
        RestDataVo data;
        try {
            if (!NumberUtils.isNumber(id)) {
                return RestDataVo.ERROR("问题参数错误");
            }
            if (getUser() == null) {
                return RestDataVo.ERROR("请登陆后关注");
            }
            if ((getUser().getUserId().equals(Long.parseLong(id)))) {
                return RestDataVo.ERROR("无法关注自己！");
            }
            data = userService.addUserFans(Long.parseLong(id), getUser().getUserId());
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }

    //查看关注的人
    @ResponseBody
    @GetMapping(value = {"/u/follow/list","/follow/list"})
    public RestDataVo userFansPage(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") String pageIndex,
                                   @RequestParam(value = "pageSize", required = false, defaultValue = "10") String pageSize,
                                   @RequestParam(value = "id", required = false) String id) {
        RestDataVo data;
        try {
            if (!NumberUtils.isNumber(pageIndex) && !NumberUtils.isNumber(pageSize)) {
                return RestDataVo.ERROR("问题参数错误");
            }
            PageVo<UserFans> page;
            if (id != null && !"".equals(id)) {
                if (!NumberUtils.isNumber(id)) {
                    return RestDataVo.ERROR("参数错误");
                }
                page = userService.getUserFansListPage(null, Long.parseLong(id), null, null, null,
                        Integer.parseInt(pageIndex), Integer.parseInt(pageSize));
            } else {
                if(getUserId()==null){
                    return RestDataVo.ERROR("参数错误");
                }
                page = userService.getUserFansListPage(null, getUserId(), null, null, null,
                        Integer.parseInt(pageIndex), Integer.parseInt(pageSize));
            }
            data = RestDataVo.PAGE(page.getList(), Integer.parseInt(pageIndex), Integer.parseInt(pageSize), page.getCount());
        } catch (Exception e) {
            data = RestDataVo.ERROR(e.getMessage());
        }
        return data;
    }


    /**
     * 查看关注的人
     *
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/u/follow/{id}")
    public RestDataVo userfollow(@PathVariable(value = "id", required = false) String id) {
        try {
            if (!NumberUtils.isNumber(id) || id == null || "".equals(id)) {
                return RestDataVo.ERROR("id参数错误");
            }
            return userService.addUserFans(Long.parseLong(id), getUserId());
        } catch (Exception e) {
            return RestDataVo.ERROR(e.getMessage());
        }
    }


    /**
     * 前台JS读取用户登录状态判断
     *
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "/status")
    public RestDataVo userSession() throws Exception {

        Map<String, Object> data = new HashMap<>(16);
        if (getUser() != null) {
            data.put("userid", getUser().getUserId());
            data.put("userName", getUser().getUserName());
            String signature;
            if (getUser().getSignature() != null) {
                signature = getUser().getSignature();
            } else {
                signature = "这个家伙很懒，啥也没留下！";
            }
            data.put("signature", signature);
            String avatar = getUser().getAvatar();
            if (avatar == null) {
                avatar = "/assets/skin/pc_theme/defalut/images/avatar/default.jpg";
            }
            data.put("avatar", avatar);
            return RestDataVo.OK("已有用户登陆", data);
        } else {
            data.put("userid", "");
            data.put("userName", "游客");
            data.put("signature", "这个家伙很懒，啥也没留下！");
            data.put("avatar", "");

            return new RestDataVo("当前没有用户登陆", RestStatusCode.FAIL, data);
        }
    }

    /**
     * 用户退出登录
     */
    @GetMapping(value = "/logout")
    @ResponseBody
    public RestDataVo logout() {
        //清除cookie、session
        userService.signOutLogin(request, response);
        return RestDataVo.OK("退出登陆成功");
    }

    /**
     * 用户提交手机号码申请获取验证码
     *
     * @param params 提交的手机号码
     *               验证码
     * @return RestDataVo
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/forget_password/getbackcode")
    public RestDataVo getBackCode(@RequestBody Map<String, Object> params) throws Exception {
        RestDataVo data;
        String username = String.valueOf(params.get("username"));
        String captcha = String.valueOf(params.get("captcha"));
        data = checkCode(captcha);
        if (data.getCode() == RestStatusCode.SUCCESS.getStatusCode()) {
            return data;
        }
        if (StringUtils.isBlank(username)) {
            return RestDataVo.ERROR("手机号码不能为空");
        }
        if (!StringHelperUtils.checkPhoneNumber(username)) {
            return RestDataVo.ERROR("手机号码错误！");
        }
        data = userService.userGetBackCode(username);
        return data;
    }

    /**
     * 用户提交邮箱地址申请获取验证码
     *
     * @param params 提交的手机号码
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/forget_password/getbackemailcode")
    public RestDataVo getEmailBackCode(@RequestBody Map<String, Object> params) throws Exception {
        String username = String.valueOf(params.get("username"));
        if (StringUtils.isBlank(username)) {
            return RestDataVo.ERROR("邮箱不能为空");
        }
        if (!StringHelperUtils.emailFormat(username)) {
            return RestDataVo.ERROR("邮箱格式错误！");
        }
        return userService.getEmailBackCode(username);
    }

    /**
     * 用户提交手机号码申请获取验证码
     *
     * @param params 用户邮箱或者手机号码
     *               验证码
     *               重新设置的新密码
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping(value = "/forget_password/update_password")
    public RestDataVo updateUserPassword(@RequestBody Map<String, Object> params) throws Exception {
        String username = String.valueOf(params.get("username"));
        String code = String.valueOf(params.get("code"));
        String password = String.valueOf(params.get("password"));
        if (StringUtils.isBlank(username)) {
            return RestDataVo.ERROR("用户名不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return RestDataVo.ERROR("验证码不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return RestDataVo.ERROR("密码不能为空");
        } else if (password.length() < 6 && password.length() > 30) {
            return RestDataVo.ERROR("密码最少6个字符，最多30个字符");
        }
        return userService.updateGetBackPassword(username, code, password);
    }


    /**
     * 校验验证码
     *
     * @param captcha
     * @return
     */
    private RestDataVo checkCode(String captcha) {
        String kaptcha = (String) session.getAttribute("kaptcha");
        // 校验验证码
        if (captcha != null) {
            if (!captcha.equalsIgnoreCase(kaptcha)) {
                return RestDataVo.ERROR("验证码错误");
            }
            session.removeAttribute(Const.KAPTCHA_SESSION_KEY);
            return RestDataVo.OK("验证码正确");
        } else {
            return RestDataVo.ERROR("验证码不能为空");
        }
    }

}
